import os
import time
#from PIL import ImageGrab

from paramsetup import Param
from lib.matchIt import *
                
def hwriter(fun):
    def hwriter_wrapper(self):
        
        fun(self)
         
        logId     = Param.logId
        buildDir  = Param.buildDir  
        OS        = Param.OS
        browser   = Param.browser
       
        f = open(buildDir +"\\"+ OS +"_" + browser +"_"+ logId +".txt","w")
        
        f.write("logId:"    + logId + "\n")
        f.write("tcname:"   + self.__class__.__name__+ "\n" )
        f.write("platform:" + platform + "\n" )        
        f.write("tester:"   + os.environ['USERNAME'] + "\n")        
        f.write("---"                           + "\n")
        f.close()
                
    return hwriter_wrapper

def bwriter(img=False):
    def bwriter_wrapper(fun):
        
        def __step(self):
            fun(self)
            user      = Param.user  
            logId     = Param.logId            
            buildDir  = Param.buildDir  
            OS        = Param.OS
            browser   = Param.browser
            tcname    = self.__class__.__name__
            
            if img:
                step        = fun.__name__  
                imagName    = OS +"_"+ browser +"_"+ logId +".png"
                imgFullPath = getImgFullPath(buildDir) + "\\" + imgName
                time.sleep(5)
               
                inn_height = user.get_eval("document.documentElement.clientHeight")
                inn_width  = user.get_eval("document.documentElement.clientWidth")
                print inn_height,inn_width

                innScreen = ImageGrab.grab((2,168,1022,672))
                innScreen.save(imgFullPath)               
                
            else:
                imgFullPath =" "
            
            logName = OS +"_" + browser +"_"+ logId +".txt"
            f = open(buildDir +"\\"+ logName,"a")
            f.write(fun.__doc__ +";"+ imgFullPath + "\n")
            f.close()
            
        return __step

    return bwriter_wrapper

def getImgFullPath(buildDir):
    if not os.path.isdir(buildDir):
        os.mkdir(buildDir)
            
        os.chdir(buildDir)
        img_dir   = os.path.join(os.pardir,'failureImages')
        if not os.path.isdir(img_dir):
            os.mkdir(img_dir)

        os.chdir(img_dir)    
        
        return os.getcwd()